import React, { useRef, FC, ReactElement } from "react";
import { ITodo } from "../typings";
interface IProps {
  addTodo: (todo: ITodo) => void;
  todoList: (todo: ITodo[]) => void;
}
const TdInput: FC<IProps> = ({ addTodo, todoList }): ReactElement => {
  const inputRef = useRef<HTMLInputElement>(null);
  const addItem = (): void => {
    const val: string = inputRef.current!.value.trim();

    if (val.length) {
      const isExist = todoList.find((todo: ITodo) => todo.content === val);
      if (isExist) return alert("该项内容已存在");

      addTodo({
        id: new Date().valueOf(),
        content: val,
        completed: false,
      });
      inputRef.current.value = "";
    }
  };

  return (
    <div className="flex w-full max-w-sm mx-auto space-x-3">
      <input
        ref={inputRef}
        type="text"
        className="flex-1 appearance-none border border-transparent w-full py-2 px-4 bg-white text-gray-700 placeholder-gray-400 shadow-md rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-purple-600 focus:border-transparent"
        placeholder="Your content"
      />
      <button
        onClick={addItem}
        className="flex-shrink-0 bg-red-400 text-white text-base font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-red-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-red-200"
      >
        添加
      </button>
    </div>
  );
};

export default TdInput;
